// TextEditor.tsx
import React, { useCallback } from "react";
import { LoadingOverlay } from "@mantine/core";
import styled, { ThemeProvider } from "styled-components";
import MonacoEditor, { loader, type OnMount, useMonaco } from "@monaco-editor/react";
import useConfig from "../../store/useConfig";
import useFile from "../../store/useFile";

// 定义主题对象
const theme = {
  colors: {
    gray: {
      0: "#f8f9fa",
      1: "#f1f3f5",
      2: "#e9ecef",
      3: "#dee2e6",
      4: "#ced4da",
      5: "#adb5bd",
      6: "#868e96",
      7: "#495057",
      8: "#343a40",
      9: "#212529",
    },
    blue: {
      5: "#228be6",
      6: "#1c7ed6",
      7: "#1971c2",
    },
  },
};

loader.config({
  paths: {
    vs: "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.52.2/min/vs",
  },
});

const editorOptions = {
  formatOnPaste: true,
  tabSize: 2,
  formatOnType: true,
  minimap: { enabled: false },
  stickyScroll: { enabled: false },
  scrollBeyondLastLine: false,
  placeholder: "Start typing...",
};

const TextEditor = () => {
  const monaco = useMonaco();
  const contents = useFile((state) => state.contents);
  const setContents = useFile((state) => state.setContents);
  const setError = useFile((state) => state.setError);
  const jsonSchema = useFile((state) => state.jsonSchema);
  const editorTheme = useConfig((state) => (state.darkmodeEnabled ? "vs-dark" : "light"));
  const fileType = useFile((state) => state.format);
  const fetchDefaultData = useFile((state) => state.fetchDefaultData);
  const [searchTerm, setSearchTerm] = React.useState("");

  const handleMount: OnMount = useCallback((editor) => {
    editor.onDidPaste(() => {
      editor.getAction("editor.action.formatDocument")?.run();
    });
  }, []);

  React.useEffect(() => {
    monaco?.languages.json.jsonDefaults.setDiagnosticsOptions({
      validate: true,
      allowComments: true,
      enableSchemaRequest: true,
      ...(jsonSchema && {
        schemas: [
          {
            uri: "http://myserver/foo-schema.json",
            fileMatch: ["*"],
            schema: jsonSchema,
          },
        ],
      }),
    });
  }, [jsonSchema, monaco?.languages.json.jsonDefaults]);

  const handleSearch = async () => {
    try {
      await fetchDefaultData(searchTerm);
    } catch (error) {
      setError("Asset not found");
    }
  };

  return (
    <ThemeProvider theme={theme}>
      <StyledEditorWrapper>
        <SearchBar>
          <input
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="输入DID:"
            onKeyPress={(e) => e.key === "Enter" && handleSearch()}
          />
          <button onClick={handleSearch}>查询</button>
        </SearchBar>
        <StyledWrapper>
          <MonacoEditor
            height="100%"
            language={fileType}
            theme={editorTheme}
            value={contents}
            options={editorOptions}
            onMount={handleMount}
            onValidate={(errors) => setError(errors[0]?.message)}
            onChange={(contents) => setContents({ contents, skipUpdate: true })}
            loading={<LoadingOverlay visible />}
          />
        </StyledWrapper>
      </StyledEditorWrapper>
    </ThemeProvider>
  );
};

// 样式组件
const SearchBar = styled.div`
  padding: 12px;
  background: ${({ theme }) => theme.colors.gray[0]};
  border-bottom: 1px solid ${({ theme }) => theme.colors.gray[3]};
  display: flex;
  gap: 10px;

  input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid ${({ theme }) => theme.colors.gray[4]};
    border-radius: 4px;
    font-size: 14px;

    &:focus {
      outline: 2px solid ${({ theme }) => theme.colors.blue[5]};
    }
  }

  button {
    padding: 8px 16px;
    background: ${({ theme }) => theme.colors.blue[6]};
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.2s;

    &:hover {
      background: ${({ theme }) => theme.colors.blue[7]};
    }

    &:active {
      transform: translateY(1px);
    }
  }
`;

const StyledEditorWrapper = styled.div`
  display: flex;
  flex-direction: column;
  height: 100vh;
  user-select: none;
`;

const StyledWrapper = styled.div`
  flex: 1;
  overflow: hidden;
`;

export default TextEditor;